﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AzureDiagMon.Common.Algorithms.FragmentedRanges
{
    public class FragmentedRangeSection<TRangeIndex> : IFragmentedRangeSection where TRangeIndex : IComparable
    {
        #region Public properties

        public TRangeIndex StartIndex { get; set; }
        public TRangeIndex EndIndex { get; set; }

        #endregion

        #region Implementation of IFragmentedRangeSection

        IComparable IFragmentedRangeSection.StartIndex { get { return StartIndex; } }
        IComparable IFragmentedRangeSection.EndIndex { get { return EndIndex; } }

        #endregion

        #region Constructors

        public FragmentedRangeSection() { }
        public FragmentedRangeSection(TRangeIndex startIndex, TRangeIndex endIndex)
        {
            //TODO: Exhange the values instead of throwing an exception?
            if (startIndex.CompareTo(endIndex) > 0)
                throw new ArgumentException("startIndex is larger than endIndex");

            StartIndex = startIndex;
            EndIndex = endIndex;
        }

        #endregion

        #region Implementation of IComparable

        public int CompareTo(object obj)
        {
            var other = obj as FragmentedRangeSection<TRangeIndex>;
            if (other == null)
                throw new NotSupportedException();

            if (StartIndex.CompareTo(other.EndIndex) < 0)
                return -1;

            if (EndIndex.CompareTo(other.StartIndex) > 0)
                return 1;

            if (EndIndex.CompareTo(other.EndIndex) < 0)
                return -1;
            if (EndIndex.CompareTo(other.EndIndex) > 0)
                return 1;

            return 0;
        }

        #endregion

        #region Overrides of Object

        public override string ToString()
        {
            return String.Format("FragmentedRangeSection: {0} - {1}", StartIndex, EndIndex);
        }

        public override bool Equals(object obj)
        {
            if (obj == this)
                return true;

            var other = obj as FragmentedRangeSection<TRangeIndex>;

            if (other == null)
                return false;

            return StartIndex.CompareTo(other.StartIndex) == 0
                   && EndIndex.CompareTo(other.EndIndex) == 0;
        }

        #endregion
    }
}
